<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
          <el-form-item label="车牌号" prop="licenseNumber">
            <el-input v-model="licenseNumber" placeholder="请输入车牌号" clearable size="small" style="width: 350px"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <!-- <el-form-item label="用户邮箱" prop="email">
            <el-input
              v-model="email"
              placeholder="请输入用户邮箱"
              clearable
              size="small"
              style="width: 350px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="用户状态" prop="status">
            <el-select
              v-model="status"
              placeholder="请选择用户状态"
              clearable
              size="small"
              style="width: 200px"
            >
              <el-option :key="0" label="正常" :value="0" />
              <el-option :key="1" label="停用" :value="1" />
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">

          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="handleDelete">删除</el-button>

            <el-button type="primary" plain icon="el-icon-delete" size="mini" @click="handleAdd">新增</el-button>
          </el-col>

          <!-- <right-toolbar
            :show-search.sync="showSearch"
            :columns="columns"
            @queryTable="getList"
          /> -->
        </el-row>

        <el-table :data="CarList" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="车辆图片" prop="carImage" align="center" width="92px">

            <template slot-scope="scope">
              <el-image style="width: 80px; height:80px; margin-bottom:-4px;;border-radius: 50%"
                :src="scope.row.carImage">
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="行驶证图片" prop="licenseImage" align="center" width="92px">

            <template slot-scope="scope">
              <el-image style="width: 80px; height:80px; margin-bottom:-4px;;border-radius: 50%"
                :src="scope.row.licenseImage">
              </el-image>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="id" label="车辆ID" align="center" width="170px" /> -->
          <el-table-column prop="carNumber" label="车牌号" align="center" width="100px" />
          <el-table-column prop="revenueMethod" label="经营方式" align="center" width="100px" />
          <el-table-column prop="brand" label="车辆品牌" align="center" width="80px" />
          <el-table-column prop="carMoney" label="购买金额（元）" align="center" width="120px" />
          <el-table-column prop="buyTime" label="购置时间" align="center" width="95px" />
          <el-table-column prop="maxUseYear" label="最大使用年限" align="center" width="110px" />
          <el-table-column prop="status" label="状态" align="center" width="50px">
            <template slot-scope="{ row }">
              <span :style="getStatusStyle(row.status)">{{ row.status }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="driverName" label="司机姓名" align="center" width="80px" />
          <el-table-column prop="driverPhone" label="司机电话" align="center" width="110px" />
          <!-- <el-table-column prop="status" label="状态" align="center">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(scope.row)"
              />
            </template>
          </el-table-column> -->


          <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
            <template v-if="scope.row.id !== 1" slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="Delete(scope.row)">删除</el-button>
              <el-button size="mini" type="text" icon="el-icon-s-finance"
                @click="handleCarLicense(scope.row)">行驶证详情</el-button>
              <!-- <el-button size="mini" type="text" icon="el-icon-s-finance"
                @click="handleDriverLicense(scope.row)">行驶证详情</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-pagination :page-size.sync="queryParams.pageSize" layout="total, sizes, prev, pager, next, jumper"
      :total="total" :page-sizes="[5, 10, 15, 20]" :current-page.sync="queryParams.pageNum"
      @current-change="handleCurrentChange" @size-change="handleCurrentChange" />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="车牌号" prop="carNumber">
              <el-input v-model="form.carNumber" placeholder="请输入车牌号" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆品牌" prop="brand">
              <el-input v-model="form.brand" placeholder="请输入车辆品牌" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="购买金额" prop="carMoney">
              <el-input v-model="form.carMoney" placeholder="请输入购买金额" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="购买时间" prop="buyTime">
              <el-input v-model="form.buyTime" placeholder="请输入购买时间" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择">
                <el-option :key="'运营'" label="运营" :value="'运营'" />
                <el-option :key="'空闲'" label="空闲" :value="'空闲'" />
                <el-option :key="'维修'" label="维修" :value="'维修'" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大使用年限" prop="maxUseYear">
              <el-input v-model="form.maxUseYear" placeholder="请输入最大使用年限" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="司机姓名" prop="driverName">
              <el-input v-model="form.driverName" placeholder="请输入司机姓名" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="司机电话" prop="driverPhone">
              <el-input v-model="form.driverPhone" placeholder="请输入司机电话" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="经营方式" prop="revenueMethod">
              <el-select v-model="form.revenueMethod" placeholder="请选择">
                <el-option :key="'运营'" label="运营" :value="'运营'" />
                <el-option :key="'挂靠'" label="挂靠" :value="'挂靠'" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="车辆图片" prop="carImage">
              <template v-if="form.carImage">
                <div>
                  <el-image v-if="form.carImage" style="width: 400px; height: 260px" :src="form.carImage"
                    :fit="fit"></el-image>
                  <button @click="deleteCarImage" v-if="form.carImage">删除图片</button>
                </div>
              </template>
              <template v-else>
                <el-upload class="upload-demo" action="http://localhost:8887/api/v1/oss/uploadImg"
                  :on-preview="handlePreview" :on-remove="handleRemove" :on-success="handleSuccess" name="img"
                  list-type="picture">
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </template>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>




    <!-- 行驶证配置对话框 -->
    <el-dialog :title="title" :visible.sync="licenseOpen" width="600px" append-to-body>
      <el-form ref="form2" :model="form2" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="图片" prop="licenseImage">
              <template v-if="form2.licenseImage">
                <div>
                  <el-image v-if="form2.licenseImage" style="width: 400px; height: 260px" :src="form2.licenseImage"
                    :fit="fit"></el-image>
                  <button @click="deleteLicenseImage" v-if="form2.licenseImage">删除图片</button>
                </div>
              </template>
              <template v-else>
                <el-upload class="upload-demo" action="http://localhost:8887/api/v1/oss/uploadImg"
                  :on-preview="handlePreview" :on-remove="handleRemove" :on-success="handleLicenseImageSuccess"
                  name="img" list-type="picture">
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </template>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="licenseSubmitForm">确 定</el-button>
        <el-button @click="licenseCancel">关 闭</el-button>
      </div>
    </el-dialog>







  </div>
</template>

<script>
import { changeUserStatus, delUser, getUserById, updateUser } from '@/api/system/user';
import { searchCarList, getCarBasicById, updateCarBasic, delCarBasic, getCarLicense, updateLicense } from '@/api/system/car';

export default {
  name: 'User',
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 5,

      },
      title: '',
      // 是否显示弹出层
      open: false,
      // 表单校验
      rules: {
        carNumber: [
          { required: true, message: '车牌号不能为空', trigger: 'blur' },
        ],
        brand: [
          { required: true, message: '车辆品牌', trigger: 'blur' }
        ],
        carMoney: [
          { required: true, message: '购买金额', trigger: 'blur' }
        ],
        buyTime: [
          { required: true, message: '购买时间', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '车辆状态', trigger: 'blur' }
        ],
        maxUseYear: [
          { required: true, message: '最大使用年限', trigger: 'blur' }
        ],
        revenueMethod: [
          { required: true, message: '经营方式', trigger: 'blur' }
        ],

      },
      // 角色选项
      roleOptions: [],
      // 显示搜索条件
      showSearch: true,
      // 遮罩层
      loading: true,
      // 用户表格数据
      userList: null,
      // 总条数
      total: 0,
      // 选中数组
      ids: [],
      // 表单参数
      form: {},
      form2: {},
      licenseNumber: "",
      email: "",
      status: "",
      revenueMethod: "",
      CarList: []
    }
  },
  watch: {},
  created() {
    this.search(this.licenseNumber, 1, this.queryParams.pageSize);
  },
  methods: {
    getStatusStyle(status) {
      if (status === '运营') {
        return 'color: green;';
      } else {
        return 'color: red;';
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.loading = true;
      this.search(this.licenseNumber, 1, this.queryParams.pageSize);
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    licenseCancel() {
      this.licenseOpen = false
      this.licenseReset()
    },
    /** 查询车辆信息列表 */
    search(licenseNumber, page, size) {
      console.log("-----------------------------");
      console.log(page);
      console.log(size);
      this.loading = true;
      searchCarList(licenseNumber, page, size).then((response) => {
        this.CarList = response.rows;
        this.total = response.total;
        this.loading = false;

      });
    },
    // 用户状态修改
    // handleStatusChange(row) {
    //   const text = row.status === '0' ? '启用' : '停用'
    //   this.$modal
    //     .confirm('确认要"' + text + '""' + row.username + '"用户吗？')
    //     .then(function () {
    //       return changeUserStatus(row.id, row.status)
    //     })
    //     .then(() => {
    //       this.$modal.msgSuccess(text + '成功')
    //     })
    //     .catch(function () {
    //       row.status = row.status === '0' ? '1' : '0'
    //     })
    // },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.title = '修改车辆信息';
      this.open = true
      console.log(row.id)
      getCarBasicById(row.id).then((response) => {
        this.form.carNumber = response.carNumber;
        this.form.brand = response.brand;
        this.form.id = response.id;
        this.form.carMoney = response.carMoney;
        this.form.buyTime = response.buyTime;
        this.form.maxUseYear = response.maxUseYear;
        this.form.driverId = response.driverId;
        this.form.driverName = response.driverName;
        this.form.driverPhone = response.driverPhone;
        this.form.status = response.status;
        this.form.carImage = response.carImage;
        this.form.licenseImage = response.licenseImage;
        this.form.revenueMethod = response.revenueMethod;
        this.carImageUrl = response.carImage;
      });
    },
    handleCarLicense(row) {
      this.licenseReset()
      this.title = '行驶证详情';
      this.licenseOpen = true;
      getCarLicense(row.id).then((response) => {
        this.form2.id = response.id
        this.form2.licenseImage = response.licenseImage;
        this.licenseImageUrl = response.licenseImage;
        console.log("---------------------------------")
        console.log(response)
      })
    },
    licenseReset() {
      this.licenseImageUrl = undefined,
        this.form2 = {
          id: undefined,
          licenseImage: undefined,
        }
      this.resetForm('form2')
    },
    // 表单重置
    reset() {
      this.carImageUrl = undefined,
        this.form = {
          id: undefined,
          carNumber: undefined,
          brand: undefined,
          carMoney: undefined,
          buyTime: undefined,
          maxUseYear: undefined,
          driverId: undefined,
          driverName: undefined,
          driverPhone: undefined,
          status: undefined,
          carImage: undefined,
          revenueMethod: undefined,
        }
      this.resetForm('form')
    },
    /** 新增用户 */
    handleAdd() {
      this.reset();
      // 初始化表单数据
      this.form = {
        phone: '',
        sex: '',
        id: '',
        name: '',
        position: '',
        password: ''
      };
      // 设置对话框标题
      this.title = '新增车辆';
      // 打开对话框
      this.open = true;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = this.ids
      this.$modal
        .confirm('是否确认删除编号为"' + ids + '"的数据项？')
        .then(function () {
          var i = 0;
          while (ids[i + 1]) {
            delCarBasic(ids[i])
            i = i + 1;
          }
          return delCarBasic(ids[i])

        })
        .then(() => {
          this.queryParams.pageNum = 1;
          this.search(licenseNumber, 1, this.queryParams.pageSize)
          this.$modal.msgSuccess('删除成功');
        })
        .catch(() => { })
    },
    Delete(row) {
      this.$modal
        .confirm('是否确认删除编号为"' + row.id + '"的数据项？')
        .then(function () {
          return delCarBasic(row.id);
        })
        .then(() => {
          this.queryParams.pageNum = 1;
          this.search(this.licenseNumber, 1, this.queryParams.pageSize)
          this.$modal.msgSuccess('删除成功');
        })
        .catch(() => { })
    },
    handleCurrentChange() {
      this.search(this.licenseNumber, this.queryParams.pageNum, this.queryParams.pageSize);
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.open = false;

          updateCarBasic(this.form.id, this.form.carNumber, this.form.brand, this.form.carMoney, this.form.buyTime, this.form.maxUseYear, this.form.driverId, this.form.driverName, this.form.driverPhone, this.form.status, this.carImageUrl, this.form.revenueMethod).then(response => {

            console.log("------------------------------------")
              console.log(response)
             
            if (response === "该车牌号已经存在") {
              console.log("------------------------------------")
              alert("该车牌号已经存在")
            } else {
              this.$modal.msgSuccess('成功');
              this.open = false;
              this.queryParams.pageNum = 1;
              this.search(this.licenseNumber, 1, this.queryParams.pageSize);
            }
          });
        }
      });
    },
    licenseSubmitForm: function () {
      this.$refs["form2"].validate((valid) => {
        if (valid) {
          this.open = false;
          updateLicense(this.form2.id, this.licenseImageUrl).then((response) => {
            this.$modal.msgSuccess('成功');
            this.open = false;
          });
        }
      });
    },
    handleSuccess(res, file) {
      console.log(res)
      this.carImageUrl = res.data
      sessionStorage.setItem("carImageUrl", this.carImageUrl)
      console.log("------------------------------------" + this.carImageUrl)
      alert(this.carImageUrl)
    },
    handleLicenseImageSuccess(res, file) {
      this.licenseImageUrl = res.data
      alert(this.licenseImageUrl)
    },
    deleteCarImage() {
      // 执行删除图片的逻辑
      this.form.carImage = undefined; // 或者设置为其他的默认值或空字符串
    },
    deleteLicenseImage() {
      this.form2.licenseImage = undefined;
    }
  }
}
</script>
